package com.xuhuan.thread.study2.productiveconsumption;

/**
 * @author huan.xu
 * @date 2021/9/30 9:50
 * @description 生产者消费者问题：利用信号灯法解决
 * 利用标志位
 */
public class ProductiveConsumptionDemo2 {
    public static void main(String[] args) {
        Program program=new Program();

        new Player(program).start();
        new Watcher(program).start();
    }
}

/**
 * 生产者
 */
class Player extends Thread {
    private Program program;

    public Player(Program program) {
        this.program = program;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                program.play("节目一");
            } else {
                program.play("节目二");

            }
        }
    }
}

/**
 * 消费者
 */
class Watcher extends Thread {
    private Program program;

    public Watcher(Program program) {
        this.program = program;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            program.watch();
        }
    }
}

/**
 * 节目
 */
class Program {
    /**
     * 节目名称
     */
    private String name;
    /**
     * 演员是否表演
     */
    private boolean flag = true;

    /**
     * 表演
     */
    public synchronized void play(String name) {
        if (!flag) {
            //观众在观看，演员等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了：" + name);
        this.name = name;
        this.flag = !this.flag;
        //通知观众观看
        this.notifyAll();
    }

    /**
     * 观看
     */
    public synchronized void watch() {
        if (flag) {
            //演员表演，观众观看
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了：" + name);
        this.flag = !this.flag;
        //通知演员表演
        this.notifyAll();
    }
}